﻿using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;

namespace MyWeb.Common
{
    public static class EmailClass
    {
        public class Email
        {
            static bool mailSent = false;
            public static string Send_Email(string SendFrom, string SendTo, string Subject, string Body)
            {
                try
                {
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");


                    bool result = regex.IsMatch(SendTo);
                    if (result == false)
                    {
                        return "Địa chỉ email không hợp lệ.";
                    }
                    else
                    {
                        SmtpClient smtp = new SmtpClient();
                        MailMessage msg = new MailMessage(SendFrom, SendTo, Subject, Body);
                        msg.IsBodyHtml = true;

                        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                        smtp.EnableSsl = true;

                        smtp.Host = "smtp.gmail.com";//Sử dụng SMTP của gmail
                        smtp.Port = 587;

                        NetworkCredential credentials = new NetworkCredential("hiepprogrammer@gmail.com", "01235349385");
                        smtp.UseDefaultCredentials = false;
                        smtp.Credentials = credentials;

                        smtp.Send(msg);
                        return "Email đã được gửi đến: " + SendTo + ".";
                    }
                }
                catch
                {
                    return "";
                }
            }

            public static string Send_Email_With_Attachment(string SendTo, string SendFrom, string Subject, string Body, string AttachmentPath)
            {
                try
                {
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                    string from = SendFrom;
                    string to = SendTo;
                    string subject = Subject;
                    string body = Body;

                    bool result = regex.IsMatch(to);
                    if (result == false)
                    {
                        return "Địa chỉ email không hợp lệ.";
                    }
                    else
                    {
                        try
                        {
                            MailMessage em = new MailMessage(from, to, subject, body);
                            Attachment attach = new Attachment(AttachmentPath);
                            em.Attachments.Add(attach);
                            em.Bcc.Add(from);
                            System.Net.Mail.SmtpClient smtp = new SmtpClient();
                            smtp.Host = "smtp.gmail.com";//Ví dụ xử dụng SMTP của gmail 
                            smtp.Send(em);
                            return "";
                        }
                        catch (Exception ex)
                        {
                            return ex.Message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            public static string Send_Email_With_BCC_Attachment(string SendTo, string SendBCC, string SendFrom, string Subject, string Body, string AttachmentPath)
            {
                try
                {
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                    string from = SendFrom;
                    string to = SendTo; //Danh sách email được ngăn cách nhau bởi dấu ";"
                    string subject = Subject;
                    string body = Body;
                    string bcc = SendBCC;
                    bool result = true;
                    String[] ALL_EMAILS = to.Split(',');
                    foreach (string emailaddress in ALL_EMAILS)
                    {
                        result = regex.IsMatch(emailaddress);
                        if (result == false)
                        {
                            return "Địa chỉ email không hợp lệ.";
                        }
                    }
                    if (result == true)
                    {
                        try
                        {
                            MailMessage em = new MailMessage(from, to, subject, body);
                            Attachment attach = new Attachment(AttachmentPath);
                            em.Attachments.Add(attach);
                            em.Bcc.Add(bcc);

                            SmtpClient smtp = new SmtpClient();
                            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                            smtp.EnableSsl = true;

                            smtp.Host = "smtp.gmail.com";//Ví dụ xử dụng SMTP của gmail
                            smtp.Port = 587;

                            NetworkCredential credentials = new NetworkCredential("xuanhiep206@gmail.com", "01235349385");
                            smtp.UseDefaultCredentials = false;
                            smtp.Credentials = credentials;

                            smtp.Send(em);

                            return "";
                        }
                        catch (Exception ex)
                        {
                            return ex.Message;
                        }
                    }
                    else
                    {
                        return "";
                    }
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            public static void Send_Email_With_BCC(string SendTo, string SendBCC, string Subject, string Body)
            {
                MailMessage msg = new MailMessage();
                msg.IsBodyHtml = true;

                string[] mailto = SendTo.Split(';');
                foreach (var s in mailto)
                {
                    if(s.Trim().Length > 0)
                    {
                        msg.To.Add(new MailAddress(s));
                    }
                }
                //msg.From = new MailAddress(FromMail);
                msg.From = new MailAddress("xuanhiep206@gmail.com", "1 2 3", System.Text.Encoding.UTF8);
                msg.Subject = Subject;
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Body = Body;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.Priority = MailPriority.High;
                msg.Bcc.Add(SendBCC);

                SmtpClient client = new SmtpClient();
                client.Credentials = new NetworkCredential("xuanhiep206@gmail.com", "01235349385");
                client.Port = 587;//or use 587            
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true;
                client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                object userState = msg;
                try
                {
                    //you can also call client.Send(msg)
                    client.SendAsync(msg, userState);
                }
                catch (SmtpException ex)
                {
                    WebMsgBox.Show(ex.Message);
                }

                //smtp.Send(msg);
            }
            static void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
            {
                MailMessage mail = (MailMessage)e.UserState;
                string subject = mail.Subject;

                if (e.Cancelled)
                {
                    string cancelled = string.Format("[{0}] Send canceled.", subject);
                    WebMsgBox.Show(cancelled);
                }
                if (e.Error != null)
                {
                    string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
                    WebMsgBox.Show(error);
                }
                else
                {
                    WebMsgBox.Show("Message sent.");
                }
                mailSent = true;
            }

            public static Boolean sendemail(String strFrom, string strTo, string strBcc , string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
            {
                Array arrToArray;
                char[] splitter = { ';' };
                arrToArray = strTo.Split(splitter);
                MailMessage mm = new MailMessage();
                mm.From = new MailAddress(strFrom);
                mm.Subject = strSubject;
                mm.Body = strBody;
                mm.IsBodyHtml = IsBodyHTML;
                mm.ReplyTo = new MailAddress(strFrom);
                mm.Bcc.Add(strBcc);
                foreach (string s in arrToArray)
                {
                    if(s != "")
                    {
                        mm.To.Add(new MailAddress(s));
                    }
                }
                if (strAttachmentPath != "")
                {
                    try
                    {
                        //Add Attachment
                        Attachment attachFile = new Attachment(strAttachmentPath);
                        mm.Attachments.Add(attachFile);
                    }
                    catch { }
                }
                SmtpClient smtp = new SmtpClient();
                try
                {
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true; //Depending on server SSL Settings true/false
                    NetworkCredential NetworkCred = new NetworkCredential();
                    NetworkCred.UserName = "xuanhiep206@gmail.com";
                    NetworkCred.Password = "01235349385";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;//Specify your port No;
                    smtp.Send(mm);
                    return true;

                }
                catch
                {
                    mm.Dispose();
                    smtp = null;
                    return false;
                }

            }
        }
    }
}
